﻿var User = require('../models/user')

//signup
module.exports.signup = function(req,res){
	// /user/signup/:userid
	// /usr/signup/1111
	//req.params.userid 可以拿到userid=1111
	// /usr/signup/1111?userid=1112
	//req.query.userid  拿到userid = 1112
	//通过post提交userid = 1113
	//req.body.userid 可以拿到post里面的data
	//偷懒，全都可以通过req.params.拿到，顺序是 1111,1113,1112
	var _user = req.body.user;
	console.log(_user);
	User.find({name:_user.name},function(err,user){
		if(err){
			console.log(err);
		}
		
		if(user.length!==0){
			return res.redirect('/signup');
		}else{
			user = new User(_user);
			user.save(function(err,user){
				if(err){
					console.log(err);
				}
				res.redirect('/admin/userlist');
			})
		}
	})
}

//signin
module.exports.signin = function(req,res){
	var _user = req.body.user;
	var name = _user.name;
	var password = _user.password;
	User.findOne({name:name},function(err,user){
		if(err){
			console.log(err);
		}
		
		if(!user){
			console.log('no such user '+name)
			return res.redirect('/');
		}

		user.comparePassword(password,function(err,isMatch){
			if(err){
				console.log(err);
			}

			if(isMatch){
				req.session.user = user;
				return res.redirect('/');			
			}
			else{
				console.log(name+' is login failed');
				return res.redirect('/');		
			}
		})
	})
}

//logout
module.exports.logout = function(req,res){
	if(req.session.user){
		delete req.session.user;
	}
	// if(app.locals && app.locals.user){
	// 	delete app.locals.user;
	// }
	res.redirect('/');
}

module.exports.userlist = function(req,res){
	User.fetch(function(err,users){
		if(err){
			console.log(err);
		}
		// console.log(users);
		res.render('userlist',{
			title:'imooc 用户列表页',
			users:users
		})
	});
}

module.exports.showSignup = function(req,res){
	res.render('signup',{
		title:'用户注册'
	})

}
module.exports.showSignin = function(req,res){
	res.render('signin',{
		title:'用户登录'
	})

}

//权限控制，需要登录
module.exports.signinRequried = function(req,res,next){
	var user = req.session.user;

	if(!user){
		return res.redirect('/signin');
	}
	next();
}
//权限控制，role>10
module.exports.adminRequried = function(req,res,next){
	var user = req.session.user;

	if(user.role <= 10){
		return res.redirect('/signin');
	}
	next();
}